//alert("load ui helper");

$(document).on("pageshow","#grouppay",function(){
    //alert("try to add event listener to group pay");
    $("#groupnum").change(function(){
        var group_num = $(this).val();
        var group_price = parseFloat($("#groupprice").attr("price")).toFixed(2);
        $("#groupnum_show").html(group_num + "份");
        $("#groupsum").html(group_price * group_num + "元");
    });
});


// =================================================
function initORDER(store_id, store_name, store_bottom_price)
{
    ORDER = {
        "store_id": store_id,
        "store_name": store_name,
        "store_bottom_price": store_bottom_price,
        "total_price" : 0.0,
        "list" : []
      };
}

function clearOrder()
{
    ORDER.total_price = 0.0;
    ORDER.list = [];
}


$(document).on("pageinit","div.store",function(){
    var store_id = $(this).attr("store_id");
    var store_name = $(this).attr("store_name");
    var store_bottom_price = $(this).attr("store_bottom_price");
    //alert("第一次进入店铺页面,初始化ORDER");
    if (window.ORDER && ORDER.total_price>0.0 && ORDER.store_id == store_id)
    {
        refreshPageByOrder();
    }
    else
        initORDER(store_id, store_name, store_bottom_price);

    function refreshPageByOrder()
    {    
        $(".item_account").html(0);    
        $(".item_account").parent().parent().attr('item_account',0);    
        $.each(ORDER.list, function(i,val){
            $("#item_account_id_"+val.item_id).html(val.item_account);
            $("#item_account_id_"+val.item_id).parent().parent().attr('item_account',val.item_account);
        });
        updatePriceInfo();
    }

    function updateORDER()
    {
        // 遍历 li.item, 从attr中获取价格、数量、名称、id 更新json
        ORDER.total_price = 0.0;
        ORDER.list = [];

        var totalPrice = 0.0;
        $.each($("li.item"), function(i,val){
            //alert($(val).attr("item_id"));
            //alert($(val).attr("item_name"));
            //alert($(val).attr("item_account"));
            //alert($(val).attr("item_price"));

            var item_id = $(val).attr("item_id");
            var item_name = $(val).attr("item_name");
            var item_account = parseInt($(val).attr("item_account"));
            var item_price = parseFloat($(val).attr("item_price")).toFixed(2);

            if (item_account > 0)
            {
                ORDER.list.push({
                    "item_id" : item_id,
                    "item_name" : item_name,
                    "item_account": item_account,
                    "item_price" : item_price,
                });

                totalPrice = totalPrice + item_account * item_price;
                ORDER.total_price = totalPrice.toFixed(1);
            }
        });
    }
    function updatePriceInfo()
    {
        $("#store_pay").text("" + ORDER.total_price + "元");
    }

    $("li.item a.add").on("tap", function(){
        var account = parseInt($(this).children("span").html());
        $(this).children("span").text(account + 1);

        // 修改隐藏表单内容

        // 修改账单报表内容

        // 修改总价内容
        var item_name = $(this).parent().children("a").children("h2").text();
        var item_id   = $(this).parent().attr("item_id");
        var item_price= $(this).parent().attr("item_price");
        $(this).parent().attr("item_name", item_name);
        $(this).parent().attr("item_account", account+1);

        updateORDER();
        updatePriceInfo();

        /*alert(item_name);
        alert(item_id);
        alert(item_price);
        */
    });

    $("li.item a.del").on("tap", function(){
        var account_obj = $(this).parent().children("a").children("span");
        var account = parseInt(account_obj.html());

        if (account > 0)
        {
            account_obj.text(account - 1);
        }

        var item_name = $(this).parent().children("a").children("h2").text();
        var item_id   = $(this).parent().attr("item_id");
        var item_price= $(this).parent().attr("item_price");
        $(this).parent().attr("item_name", item_name);
        $(this).parent().attr("item_account", account-1);

        updateORDER();
        updatePriceInfo();

        /*alert(item_name);
        alert(item_id);
        alert(item_price);*/
    });

    $("#clear_bill").on("tap", function(){
        clearOrder();
        refreshPageByOrder();
    });
});

$(document).on("pagebeforeshow","div.store",function(){
    var store_id = $(this).attr("store_id");
    var store_name = $(this).attr("store_name");
    if (ORDER.store_id != store_id)
    {
        alert("进入不同页面,重新初始化ORDER");
        initORDER(store_id, store_name);
    } 
});

$(document).on("pagebeforeshow","#general_pay",function(){ // 当进入页面二时
    function displayBill()
    {
        $("#gen_bill").html("");
        $.each(ORDER.list, function(i,val){
            var oriText = $("#gen_bill").html();
            var newText = oriText + "<p>" + val.item_name + "<span style='float:right;'>" + val.item_account + "份</span></p>"
            $("#gen_bill").html(newText);
        });
        var oriText = $("#gen_bill").html();
        var offset = 0.001;
        if ( ORDER.total_price > ORDER.store_bottom_price-offset)
        {
            var newText = oriText + "<p style='float:right;'>共计 " + ORDER.total_price + " 元</p>";
            $("#gen_bill").html(newText);
            $("#gen_billsubmit").button("enable");
        }
        else
        {
            var newText = oriText +"<p style='float:right;'>共计" + ORDER.total_price 
                            + " 元(起售价"+ORDER.store_bottom_price+"元)</p>";
            $("#gen_bill").html(newText);
            $("#gen_billsubmit").button( "disable");
        }
    }

    function updateBillJson () {
        $("#gen_billjson").val(JSON.stringify(ORDER));
    }    

    $("#gen_billsubmit").on("tap", function(){
        clearOrder();
    });    

    displayBill();
    updateBillJson();
});

// 去掉商品列表左右两侧的空白; 因为使用没有作用，所以使用jquery
$(document).on("pageshow",".store",function(){ // 当进入页面二时
  $(".ui-collapsible-content").css({"padding-left":"0px","padding-right":"0px"});
});

// ===============================================

$(document).on("pageinit", "#shop", function(event,data){
    // 载入ajax tab后，刷新tab下的listview
    /*
    $(".tabs").on( "tabsload", function( event, ui ) {
         $("#ui-tabs-1 ul").listview();
      });
    */
});

function checkName(name)
{
    if (name=="")
        return false;
    else return true;
}

function checkPhone(phone)
{        
    var reg = /^0?1[3|4|5|8][0-9]\d{8}$/;
    if (reg.test(phone)) {
        return true;
    }else{
        return false;
    };
}

function checkAddress(address)
{
    if (address=="")
        return false;
    else return true;
}

function checkMail(mail)
{
    var reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
    if (reg.test(mail)) {
        return true;
    }else{
        return false;
    };
}

$(document).on("pagebeforeshow", "#general_pay", function(event,data){  //外卖下单检查
    $("#general_pay_form").submit(function(){
        name = $("#general_pay_name").val();
        phone = $("#general_pay_phone").val();
        address = $("#general_pay_address").val();
        alertString = "";
        flag = true;
        if (!checkName(name))
        {
            alertString += "姓名不能为空";
            flag = false;
        }
        if (!checkPhone(phone))
        {
            if (alertString == "")
                alertString += "手机号码有误";
            else 
                alertString += ",手机号码有误";
            flag = false;
        }
        if (!checkAddress(address))
        {
            if (alertString == "")
                alertString += "地址不能为空";
            else 
                alertString += ",地址不能为空";
            flag = false;
        }
        if (alertString!="")
            alert(alertString);
        return flag;
    });  
});

$(document).on("pagebeforeshow", "#grouppay", function(event,data){  //团购下单检查
    $("#group_pay_form").submit(function(){
        name = $("#group_pay_name").val();
        phone = $("#group_pay_phone").val();
        mail = $("#group_pay_mail").val();
        alertString = "";
        flag = true;
        if (!checkName(name))
        {
            alertString += "姓名不能为空";
            flag = false;
        }
        if (!checkPhone(phone))
        {
            if (alertString == "")
                alertString += "手机号码有误";
            else 
                alertString += ",手机号码有误";
            flag = false;
        }
        if (!checkMail(mail))
        {
            if (alertString == "")
                alertString += "邮箱地址有误";
            else 
                alertString += ",邮箱地址有误";
            flag = false;
        }
        if (alertString!="")
            alert(alertString);
        return flag;
    });  
});


// ===============================================
// Below is for group shop slider pictures
$(document).on("pageshow","#groupshop",function(){
    // Initialize
    

    $(document).ready(function(){

        slider = $('.bxslider').bxSlider({
        });
        // $(".sliderimg").load(function(){
        //     slider.reloadSlider();  
        // });
        
    });





});